applyMiddleware middleware要分三次执行,才能获得最终的效果。
第一次传入middlewareAPI,即可以访问getState()和dispatch()的store
第二次传入next,是对其内层middleware闭包的引用
第三次传入action,并且使用next(action)的形式来传递action
一个典型的middleware的形式为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 export const crashReporter = store => next => action => { try { return next(action) } catch (err) { if (process.env.NODE_ENV !== 'production' ) { console .log('Caught an exception in Redux' , err) } } }
applyMiddleware将多个middleware加入dispatch的流程中,在其之前和之后都进行一次拦截处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 export default function applyMiddleware (...middlewares ) { return createStore => (...args) => { const store = createStore(...args) let dispatch = () => { throw new Error ( `Dispatching while constructing your middleware is not allowed. ` + `Other middleware would not be applied to this dispatch.` ) } const middlewareAPI = { getState: store.getState, dispatch: (...args ) => dispatch(...args) } const chain = middlewares.map(middleware => middleware(middlewareAPI)) dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }